﻿using System;
using System.Net;
using System.Text;

namespace MediaBot.Library
{
    public class CustomWebRequest : IDisposable
    {
        public string Header { get; set; }
        public readonly WebHeaderCollection Headers;
        private bool KeepAlive { get; set; }
        public string Method { get; private set; }
        private CustomWebReponse Reponse { get; set; }
        public Uri RequestUri { get; private set; }
        public int Timeout { private get; set; }
        public CookieCollection Cookies;

        public CustomWebRequest(Uri uri)
        {
            Headers = new WebHeaderCollection();
            Cookies = new CookieCollection();
            RequestUri = uri;
            Headers["Host"] = uri.Host;
            Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
            KeepAlive = true;
            if (KeepAlive)
                Headers["Connection"] = "Keep-Alive";
            Method = "GET";
        }      

        public CustomWebReponse GetResponse()
        {
            if (Reponse == null || Reponse.Socket == null || Reponse.Socket.Connected == false)
            {
                Reponse = new CustomWebReponse();
                Reponse.Connect(this);
                Reponse.SetTimeout(Timeout);
            }
            Reponse.SendRequest(this);
            Reponse.ReceiveHeader();
            return Reponse;
        }

        public void Dispose()
        {
            if(Reponse != null) Reponse.Dispose();
            this.Cookies = null;
            GC.Collect();
        }

        public void AddCookie(Cookie cookie)
        {
            this.Cookies.Add(cookie);
        }

        public string GetCookies()
        {
            StringBuilder sb = new StringBuilder();

            foreach (Cookie cookie in this.Cookies)
            {
                sb.Append(cookie.Name + "=" + cookie.Value);
            }
            return sb.ToString();
        }
    }
}